package main

import (
	"fmt"
	"log"
	"os"
	"os/signal"
	"runtime"
	"syscall"
	"time"

	_ "gitee.com/shiwjlinux/arm/apps"
	"gitee.com/shiwjlinux/arm/clients/agent"
	clients "gitee.com/shiwjlinux/arm/clients/restful"
	"gitee.com/shiwjlinux/arm/common"
)

// const PERFORMANCE_TEST = false // 是否开启性能测试，如果是，则会一直循环采集发送，如果否，则一分钟采集一次
const Interval = 60

func main() {
	// 创建一个channel来接收系统信号
	sigChan := make(chan os.Signal, 1)
	// 监听 SIGINT (Ctrl+C) 和 SIGTERM 信号
	signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)

	var client *clients.Client
	if common.IsAndroid() {
		client = clients.NewClient("http://172.20.11.5:9999")
	} else {
		client = clients.NewClient("http://127.0.0.1:9999")
	}
	hostAgent, err := agent.NewHostAgent(client, Interval*time.Second)
	if err != nil {
		log.Fatalf("Failed to create host agent: %v", err)
	}

	// 创建实例代理，设置报告间隔
	instanceAgent, err := agent.NewInstanceAgent(client, Interval*time.Second)
	if err != nil {
		log.Fatalf("Failed to create instance agent: %v", err)
	}

	// 启动
	hostAgent.Start()
	// 启动
	instanceAgent.Start()

	printGoroutineInfo()
	// 等待信号
	sig := <-sigChan
	log.Printf("Received signal: %v, starting graceful shutdown...", sig)

	// 优雅停止
	instanceAgent.Stop()
	hostAgent.Stop()
	log.Println("Service stopped gracefully")
	// select {}
}

func printGoroutineInfo() {
	numGoroutines := runtime.NumGoroutine()
	fmt.Printf("当前goroutine数量 %d\n", numGoroutines)
}
